import React, { Component } from "react";
import {
    StyleSheet,
    Text,
    View,
    Platform,
    TextInput,
    TouchableOpacity,
    DeviceEventEmitter,
    NativeAppEventEmitter,
    ScrollView,
    Switch,
    Button,
    InteractionManager,
  Dimensions
} from "react-native";

import Toast from "react-native-sk-toast";
import ImagePicker from 'react-native-image-picker';
import api from "../../services/api";
import _ from "lodash";
import moment from "moment";
import styles from "./serviceCompletionStyle";
import ToastTip from "../global/ToastTip";
import LoadingTip from "../global/LoadingTip";
import dismissKeyboard from "dismissKeyboard";
import * as config from "../../constants/apiConfig";
import DeviceStorage from '../global/DeviceStorage';
const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');
// import Touch from '../global/Touch';

class NursingServiceCompletion extends Component {
    constructor(props) {
        super(props);
        this.state = {
            obj_price: "",
            showLoading: false,
            btnDisabled: false,
            isPay: false,
            serviceCostDetail: "",
            serviceCost: ""
        };
    }

    componentDidMount(){
        let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
        this._subcribOrder = Emitter.addListener('pop', this.pop.bind(this));
    }

    componentWillMount() {}

     componentWillUnmount(){
        this._subcribOrder && this._subcribOrder.remove();
        // let {actions, dispatch} = this.props;
        // await this._createSession();
    }

    pop(){
        setTimeout(()=>{
            this.props.navigator.pop();
            let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
            Emitter.emit("order.onload");
        }, 500);
    }

    async _submitAction() {
        let { order_info, session, navigator } = this.props;
        let { serviceCost,serviceCostDetail } = this.state;

        // console.log("@@@", obj_price);

        if (!serviceCost) {
            this.refs.toast.show("请输入服务金额");
            return;
        }

        if (parseFloat(serviceCost) == 0) {
            this.refs.toast.show("请输入大于零的金额");
            return;
        }

        // if (order_info.orderType == "nursing" && order_info.needUploadImage) {
        //     this._getObj(order_info,serviceCost,serviceCostDetail);
        //     return;
        // }

        this.setState({ showLoading: true, btnDisabled: true });

        // let send_res = await api.post("/wx/customsend");
        // let res = await api.post("/order/setServiceCost",{id:order_info.id,serviceCost,serviceCostDetail});
        // if (res.cd == 1){
        //     this.setState({ showLoading: false , btnDisabled: false});
        //     Toast.bottom(res.msg);
        //     return;
        // }
        let needPay = this.state.isPay?1:0;
        order_info = {...order_info, unservedCost:serviceCost,unservedCostDetail:serviceCostDetail,unservedCostPayStatus:needPay}
        this._getComplete(order_info,true)
        // if(res.data){
        //     // let { actions, dispatch } = this.props;
        //     navigator.pop();
        //     let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
        //         Emitter.emit("order.onload");

        //     // dispatch(
        //     //     actions.order.order_done_obj_price(order_info.id)
        //     // ).then(() => {
        //     //     this.setState({ showLoading: false });
        //     //
        //     // });

        // }else{
        //     this.setState({ showLoading: false , btnDisabled: false});
        //     Toast.bottom("该笔订单已设置服务金额，请刷新后重试");
        // }

    }




    confirmService = async () => {
        // let { actions, dispatch,navigator, order_info, changeBtn} = this.props;
        // dispatch(actions.order.order_done_obj_price(order_info.id)).then(() => {
        //     this.setState({ showLoading: false });
        //     // changeBtn?changeBtn():null;
        //     navigator.pop();
        // });
        // this.props.completeTask?this.props.completeTask():null;

        let { session, order_info} = this.props;
        this.setState({ completeActionDisabled: true,showLoading: true,  });

        // if (order_info.orderType == "nursing" && order_info.needUploadImage) {
        //     this._getObj(order_info);
        //     return;
        // }
        // this._updateStatus(order_info);
        this._getComplete(order_info,true)

    };

    async _getComplete(info,isLoading){

        if (isLoading) {
            
        }else{
            this.setState({showLoading:true, submitDisabled: true});
        }

        // let order = this.props.order_detail;
        // if (order.service_type == 'express') {
        let {serviceFee} = this.props;
        if (serviceFee&&serviceFee.id) {
            info = {...info,serviceFeeId:serviceFee.id}
            info.status = 0;
        }
        // }
        

        

        let copyInfo = {...info};

        console.log('test---------------------create',copyInfo);
        let res = await api.post('/order/createorder',copyInfo);

        if(res.cd == 1){
            this.setState({showLoading:false, btnDisabled: false});
            this.refs.toast.show(res.msg, 3000);
            return;
        }

        // 清空地址信息
        let { session , actions, dispatch} = this.props;
        // let action;
        // if(copyInfo.service_type == 'send'){
        //     action = actions.order.order_clearaddress();
        //     await dispatch(action);
        // }else if (copyInfo.service_type == 'buy'){
        //     action = actions.order.order_clearbuyaddress();
        //     await dispatch(action);
        // }

        DeviceStorage.delete("@order@nursing");

        let ownerInfo = await api.post('/account/findUserByPhone',{phone: copyInfo.user_phone});
        let content = "";
        // if(copyInfo.service_type == "express" || copyInfo.service_type == "lockkey"){
        //     content = "您的"+ (copyInfo.service_type == "express"?"代取快递":"保管钥匙") +"订单已确认。<a href='" + config.WEB_BASE_URL + "/housekeeper/orderdetail?id="+res.data.id+"'>查看详情</a>"
        // }else{
        //     content = "您的"+ (copyInfo.service_type == "other"?copyInfo.other_service_content:copyInfo.obj_name) +"订单已确认。<a href='" + config.WEB_BASE_URL + "/housekeeper/orderdetail?id="+res.data.id+"'>查看详情</a>";
        // }
        //
        // let json = JSON.stringify({
        //                 "touser":ownerInfo.data.wxOpenId,
        //                 "msgtype":"text",
        //                 "text":
        //                 {
        //                      "content": content,
        //                 }
        //             });
        //
        // let send_res = await api.post('/wx/customsend',{json});
        if(copyInfo.isThirdParty == 1 || (session.user.role == 1 && session.user.village)){
            Toast.bottom("订单已生成，请实时跟踪并更新订单状态");
        }else{
            Toast.bottom("提交成功");
        }

        setTimeout(async ()=>{
            let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
            this.setState({showLoading:false, btnDisabled: false},() => {
                Emitter.emit("order.create_success");
                this.props.navigator.popToRoot();
                if(this.props.order_phone){//从消息直接添加订单过来
                    this.props.navigator.switchToTab({
                      tabIndex: 2
                    });
                }

                
                Emitter.emit("order.onload", copyInfo.service_type, "");
            });

        }, 100);

    }


    // async _getObj(info,serviceCost,serviceCostDetail){

    //     var options = {
    //         title: '拍照获取物品照片',
    //         cancelButtonTitle: "取消",
    //         takePhotoButtonTitle:'拍照',
    //         chooseFromLibraryButtonTitle:'选择相册',
    //         permissionDenied: {
    //           title: '提示',
    //           text: '没有拍照和获取相册权限',
    //           reTryTitle: '重试',
    //           okTitle: '确定',
    //         },
    //         quality: 0.8,
    //         maxHeight: parseInt(deviceHeight*2),
    //         maxWidth: parseInt(deviceWidth*2),
    //         storageOptions: {
    //             skipBackup: true,
    //             path: 'images'
    //         }
    //     };
    //     // 照片
    //     ImagePicker.showImagePicker(options, (response)  => {
    //         // Same code as in above section!
    //         if (response.error) {
    //         }else{
    //             if (response.didCancel) {
    //                return;
    //             }

    //             InteractionManager.runAfterInteractions(() => {
    //                 this.props.navigator.push({
    //                     title: '确认物品照片',
    //                     screen: 'housekeeperapp.imagepicker',
    //                     backButtonTitle:'',
    //                     passProps: {
    //                         from:'completion',
    //                         orderId: info.id,
    //                         orderType: info.orderType,
    //                         fileUri:response.uri,
    //                         otherServiceType:info.otherServiceType,
    //                         fileName:response.fileName,
    //                         status:info.status,
    //                         needPay:this.state.isPay,
    //                         serviceCost:serviceCost,
    //                         serviceCostDetail:serviceCostDetail,
    //                         orderPhone:info.user_phone
    //                         // source: 'data:image/jpeg;base64,' + response.data
    //                     },
    //                     navigatorStyle:{
    //                         tabBarHidden: true,
    //                         navBarTextColor: 'white',
    //                         navBarButtonColor: 'white',
    //                         navBarBackgroundColor: '#EA5404',
    //                         statusBarColor: '#EA5404',
    //                         navBarTitleTextCentered: true,
    //                         topBarElevationShadowEnabled:false
    //                     },
    //                     navigatorButtons: {
    //                         leftButtons:[
    //                             {
    //                                 id: 'back',
    //                                 icon: require("../../../img/hk_back_icon.png")
    //                             }
    //                         ]
    //                     }
    //                 });
    //             });
    //         }

    //     });

    // }

    // async _updateStatus(order_info){
    //     let {session} = this.props;
    //     let res = await api.post("/order/updatestatus", {
    //         id: order_info.id,
    //         status: 4,
    //         cancelReason:''
    //     });

    //     if(res.cd == 1){
    //         Toast.bottom(res.msg);
    //         return;
    //     }

    //     if (res.data) {
    //         let ownerInfo = await api.post("/housekeeper/ownerinfobyphone", {
    //             phone: order_info.user_phone
    //         });


    //         if (ownerInfo.data) {
    //             let send_text = "";
    //             let orderTrack = await api.post("/order/tracksdetail", {
    //                 id: order_info.id
    //             });
    //             if (orderTrack.data) {
    //                 let delayTime = (
    //                     (moment(orderTrack.data.order_endsend_time) -
    //                         moment(orderTrack.data.order_hkget_time)) /
    //                     60000
    //                 ).toFixed(0);

    //                 // let { session } = this.props;
    //                 let web_base_url = "";
    //                 if (session && session.user && session.user.product && session.user.product.baseUrl) {
    //                     web_base_url = session.user.product.baseUrl;
    //                 }else{
    //                     web_base_url = config.WEB_BASE_URL;
    //                 }


    //                 if (order_info.orderType == 'other' && order_info.othertype == 'activity') {
    //                     send_text =
    //                         "您的订单已完成。<a href='" +
    //                         web_base_url +
    //                         "/weichart/order?order_id=" +
    //                         order_info.id +
    //                         "&type=ORDER_REWARD&othertype="+order_info.othertype+"'>评价服务</a>";
    //                 }else if (order_info.orderType == 'nursing') {
    //                     send_text =
    //                         "您的订单已完成。<a href='" +
    //                         web_base_url +
    //                         "/weichart/order?order_id=" +
    //                         order_info.id +
    //                         "&type=ORDER_REWARD&othertype=nursing'>评价服务</a>";
    //                 }else{
    //                     send_text =
    //                         "您的订单已完成，耗时" +
    //                         delayTime +
    //                         "分钟。<a href='" +
    //                         web_base_url +
    //                         "/weichart/order?order_id=" +
    //                         order_info.id +
    //                         "&type=ORDER_REWARD&othertype="+order_info.othertype+"'>评价服务</a>";
    //                 }
                    
    //                 let json = JSON.stringify({
    //                     touser: ownerInfo.data.wxOpenId,
    //                     msgtype: "text",
    //                     text: {
    //                         content: send_text
    //                     }
    //                     // "customservice":
    //                     // {
    //                     //     "kf_account": session && session.user.kf_account
    //                     // }
    //                 });

    //                 let send_res = await api.post("/wx/customsend", { json });
    //             }
    //         } else {
    //             // this.refs.toast.show('绑定的用户不存在');
    //         }

    //         this.props.navigator.pop();
    //         let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
    //             Emitter.emit("order.onload");

    //     }else{
    //         Toast.bottom("该笔订单已完成，请刷新后重试");
    //     }
    // }

    _renderPrice = () => {
        return (
            <View style={styles.content}>
                <View
                    style={[
                        styles.formItem1,
                        {
                            borderBottomWidth: 0,
                            height: 90,
                            flex: 1,
                            flexDirection: "row",
                            alignItems: "flex-start",
                            alignContent:"flex-start"
                        }
                    ]}
                >
                    <Text
                        style={[
                            styles.leftText,
                            { marginLeft: 15, marginTop: 10 }
                        ]}
                    >
                        服务费用明细
                    </Text>
                    <TextInput
                        value={this.state.serviceCostDetail}
                        onChangeText={text => {
                            this.setState({ serviceCostDetail: text });
                        }}
                        style={[styles.itemRight, styles.otherContent]}
                        editable={true}
                        clearButtonMode={"while-editing"}
                        multiline={true}
                        underlineColorAndroid={"#ffffff"}
                        placeholder={"请输入服务费用的详细内容"}
                        placeholderTextColor={"#B5B5B5"}
                    />
                </View>
                <View
                    style={{ flex: 1, height: 15, backgroundColor: "#f3f3f3" }}
                />
                <Text style={[styles.titleStyle,{marginTop:10}]}>请输入服务金额</Text>
                <View style={styles.inputContent}>
                    <Text style={styles.subStyle}>¥</Text>
                    <TextInput
                        style={styles.inputStyle}
                        editable={true}
                        autoFocus={Platform.OS == "ios" ? true : false}
                        value={this.state.serviceCost}
                        ref={component => (this._inputComp = component)}
                        keyboardType={"numeric"}
                        clearButtonMode={"while-editing"}
                        underlineColorAndroid={"#ffffff"}
                        placeholder={""}
                        onChangeText={text => {
                            let { serviceCost } = this.state;
                            if (text && !/^\d+(\.\d{0,2})?$/.test(text)) {
                                this.setState({ serviceCost });
                                return;
                            }

                            this.setState({ serviceCost: text });
                        }}
                        placeholderTextColor={"#B5B5B5"}
                    />
                </View>
                <TouchableOpacity
                    disabled={this.state.btnDisabled}
                    onPress={this._submitAction.bind(this)}
                    style={styles.submitActionPhoneBtn}
                >
                    <Text style={styles.submitActionText}>确定</Text>
                </TouchableOpacity>
            </View>
        );
    };

    render() {
        let { session, order_info, message } = this.props;
        if (!session) {
            return null;
        }
        return (
            <View
                style={styles.wrapper}
                onStartShouldSetResponderCapture={e => {
                    const focusField = TextInput.State.currentlyFocusedField();
                    if (
                        focusField != null &&
                        e.nativeEvent.target != focusField
                    ) {
                        dismissKeyboard();
                    }
                }}
            >
                <ScrollView style={styles.container}>
                    <View
                        style={[
                            styles.formItem,
                            {
                                flex: 1,
                                borderBottomWidth: 0,
                                height: 44,
                                // alignItems: "flex-start",
                                justifyContent: "space-between",
                                backgroundColor: "#fff",
                                marginTop: 15
                            }
                        ]}
                    >
                        <Text style={[styles.leftText, { marginLeft: 15 }]}>
                            是否需要支付服务费用
                        </Text>
                        <Switch
                            onTintColor="#0090fa"
                            thumbTintColor="#0090fa"
                            value={this.state.isPay}
                            onValueChange={() => {
                                this.setState({ isPay: !this.state.isPay });
                            }}
                        />
                    </View>
                    {this.state.isPay ? (
                        this._renderPrice()
                    ) : (
                        <TouchableOpacity
                            disabled={this.state.btnDisabled}
                            onPress={this.confirmService}
                            style={[
                                styles.submitActionPhoneBtn,
                                { marginTop: 100 }
                            ]}
                        >
                            <Text style={styles.submitActionText}>确定</Text>
                        </TouchableOpacity>
                    )}
                </ScrollView>
                <ToastTip ref="toast" />
                <LoadingTip show={this.state.showLoading} />
            </View>
        );
    }
}

var connectHelper = require("../../services/connectHelper");
NursingServiceCompletion = connectHelper(state => state)(NursingServiceCompletion);

module.exports = NursingServiceCompletion;
